<?php

namespace app\order\logic;

use app\api\logic\CheckLogic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class OrdertrackLogic extends BasicLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit            = $params['limit'] ?? 10;
        $order_id         = $params['order_id'] ?? 0;
        $shop_id          = $params['shop_id'] ?? 0;
        $create_time      = $params['createtime'] ?? "";
        $track_number     = $params['tracking_number'] ?? "";
        $track_status     = $params['payout_status'] ?? "ALL";
        $provider_name    = $params['provider_name'] ?? "";
        $platform_track   = $params['platform_track'] ?? "";
        $where            = [];

        if (!empty($create_time)){
            $where[] = ['create_time', '>=', $create_time['0']];
            $where[] = ['create_time', '<=', $create_time['1']];
        }

        if (!empty($track_status)){
            if ($track_status !== "ALL"){
                $where[] = ['latest_status', '=', $track_status];
            }
        }

        if (!empty($provider_name)){
            $where[] = ['provider_name', '=', $provider_name];
        }

        if (!empty($track_number)){
            $where[] = ['track_number', '=', $track_number];
        }



        if($platform_track=="0" || $platform_track>0){
            $where[] = ['platform_track', '=', $platform_track];
        }

        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if(!empty($order_id)){
            $where[] = ['order_id','like', '%'.$order_id.'%'];
        }else{
            $where[] = ['order_id','>', 0];
        }
        // halt($where);
        
        $list = Db::name('order_track')
            ->field('id,order_id,shop_id,platform_track,track_number,tracking_list,latest_status,latest_sub_status,create_time,update_time')
            ->where($where)
            ->order('update_time desc')
            ->paginate($limit);
        
        $lists = $list->items();

        //批量获取订单数据;
        $order_ids      = array_column($lists,'order_id');
        $order_info     = Db::name('order_achievement')->where('order_id','in',$order_ids)->field('subtotal_price,order_id,spu,sku,createtime,name')->select()->toArray();
        $order_info_map = array_column($order_info,null,'order_id');
        foreach($lists as $k=>$v){
               $order_list                  = $order_info_map[$v['order_id']]??'';
               $track_list                  = $v['tracking_list'] ? json_decode($v['tracking_list'],true) : [];
               $current                     = $track_list ? current($track_list):'';
               $lists[$k]['sales_price'] = $order_list['subtotal_price']??'';
               $lists[$k]['spu']            = $order_list['spu']??'';
               $lists[$k]['order_number']            = $order_list['name']??'';
               $lists[$k]['createtime']      = $order_list['createtime']??'';
               if($lists[$k]['createtime'] > 0){
                    $lists[$k]['createtime'] = date('Y-m-d',$lists[$k]['createtime']);
               }
               if($lists[$k]['update_time'] > 0){
                    $lists[$k]['update_time'] = date('Y-m-d',strtotime($v['update_time']));
               }
               $spu                         = $order_list['spu']??'';
               $one_spu                     = $spu ? explode(',',$spu): '';
               $lists[$k]['spu_one']        = $one_spu ? current($one_spu) : '';
               $lists[$k]['seller_sku']     = $order_list['sku']??'';
               $lists[$k]['track_status']   = $v['latest_status']??'';
               $lists[$k]['deliver_time']   = $current['time_raw']??'';
        }
        $shop_ids     = array_column($lists,'shop_id');
        $shops        = Db::name('shops')->field('id as shop_id,name')->where('id','in',$shop_ids)->select()->toArray();
        $shops_map    = array_column($shops,null,'shop_id');
        foreach($lists as $k=>$v){
            $shops_name             = $shops_map[$v['shop_id']]??[];
            $lists[$k]['image_url'] = '';
            $lists[$k]['shop_name'] = $shops_name['name']??'';
        }
        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['物流单号', 'track_number'];
        $header[] = ['物流状态', 'track_status'];
        $header[] = ['销售额', 'sales_price'];
        $header[] = ['更新时间', 'update_time'];
        $header[] = ['订单时间', 'createtime'];
        $header[] = ['妥投时间', 'deliver_time'];

        $tableName = "Ordertrack";

        $where = [];
        $order_id         = $params['order_id'] ?? 0;
        $shop_id          = $params['shop_id'] ?? 0;
        $create_time      = $params['createtime'] ?? "";
        $track_number     = $params['tracking_number'] ?? "";
        $track_status     = $params['payout_status'] ?? "ALL";
        $provider_name    = $params['provider_name'] ?? "";
        $platform_track   = $params['platform_track'] ?? "";

        if (!empty($create_time)){
            $where[] = ['create_time', '>=', $create_time['0']];
            $where[] = ['create_time', '<=', $create_time['1']];
        }

        if (!empty($track_status)){
            if ($track_status !== "ALL"){
                $where[] = ['latest_status', '=', $track_status];
            }
        }

        if (!empty($provider_name)){
            $where[] = ['provider_name', '=', $provider_name];
        }

        if (!empty($track_number)){
            $where[] = ['track_number', '=', $track_number];
        }



        if($platform_track=="0" || $platform_track>0){
            $where[] = ['platform_track', '=', $platform_track];
        }

        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }

        if(!empty($order_id)){
            $where[] = ['order_id','like', '%'.$order_id.'%'];
        }else{
            $where[] = ['order_id','>', 0];
        }
        // halt($where);
        
        $lists = Db::name('order_track')
            ->field('id,order_id,shop_id,platform_track,track_number,tracking_list,latest_status,latest_sub_status,create_time,update_time')
            ->where($where)
            ->order('update_time desc')
            ->select()->toarray();

        //批量获取订单数据;
        $order_ids      = array_column($lists,'order_id');
        $order_info     = Db::name('order_achievement')->where('order_id','in',$order_ids)->field('subtotal_price,order_id,spu,sku,createtime,name')->select()->toArray();
        $order_info_map = array_column($order_info,null,'order_id');

        $shop_ids     = array_column($lists,'shop_id');
        $shops        = Db::name('shops')->field('id as shop_id,name')->where('id','in',$shop_ids)->select()->toArray();
        $shops_map    = array_column($shops,null,'shop_id');

        foreach($lists as $k=>$v){
            $order_list                  = $order_info_map[$v['order_id']]??'';
            $lists[$k]['order_number']   = $order_list['name']??'';
            $shops_name             = $shops_map[$v['shop_id']]??[];
            $lists[$k]['shop_name'] = $shops_name['name']??'';
            $lists[$k]['track_status']   = $v['latest_status']??'';
            $lists[$k]['sales_price'] = $order_list['subtotal_price']??'';
            $lists[$k]['createtime']      = $order_list['createtime']??'';
            if($lists[$k]['createtime'] > 0){
                $lists[$k]['createtime'] = date('Y-m-d',$lists[$k]['createtime']);
            }
            $track_list                  = $v['tracking_list'] ? json_decode($v['tracking_list'],true) : [];
            $current                     = $track_list ? current($track_list):'';
            $lists[$k]['deliver_time']   = $current['time_raw']??'';
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    /**
    * @desc    物流轨迹信息
    * @date    2024/12/23
    * @author  zhangheng
    */
    public function trackinfo($params = [])
    {
        $track_number = $params['track_number'] ?? '';
        if(empty($track_number)){
            return json(DefaultResponse(400, false, '物流单号不能为空'));
        }
        //传订单号 查询物流轨迹以及订单信息
        $data = $this->TrackQuery($track_number);
        return $this->jsonMessage(200, true, '获取成功', $data);
    }

    /**
     * @desc    获取物流状态信息
     * @date    2024/12/29
     * @author  zhangheng
     */
    public function get_track_status(){
        $size_type   = Config('Logisticskey.track_info.status');
        $info        = getLevel($size_type);
        $arr[] = [
            'value'      => "ALL",
            'label'      => "所有",
        ];
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }


    /**
     * @desc    获取物流状态信息
     * @date    2024/12/29
     * @author  zhangheng
     */
    public function get_sub_status($params){
        $platform_track = $params['platform_track']??'0';
        if($platform_track =='1'){
            $size_type   = Config('Logisticskey.718_info.sub_status');
        }elseif($platform_track =='2'){
            $size_type   = Config('Logisticskey.4px_track.sub_status');
        }else{
            $size_type   = Config('Logisticskey.track_info.sub_status');
        }

        $info        = getLevel($size_type);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功!',$arr);
    }










    /**
    * @desc    物流轨迹信息
    * @date    2024/12/24
    * @author  zhangheng
    */
    public function TrackQuery($track_number)
    {
        $where[] = ['track_number', '=', $track_number];
        $info    = Db::name('order_track')
            ->field('*')
            ->where($where)
            ->find();
        if(!$info){
            (new CheckLogic())->track_4px(['track_number'=>$track_number]);
        }
        $info['receive_country'] = $info['receive_country']??'US';
        $info['tracking_list']   = isset($info['tracking_list']) ? json_decode($info['tracking_list'],true) : [];
        return $info;
    }
    
}
